package core

import (
	"fmt"
	"github.com/vmihailenco/msgpack"
	"mj/entity"
	"strconv"
)

type Packet struct{}

func (p *Packet) Encod(message entity.Message, cmd, scmd int) ([]byte, error) {
	res, err := msgpack.Marshal(message)
	if err != nil {
		fmt.Printf("序列化失败")
		return nil, err
	}
	//$sendStr = pack('N', strlen($sendStr) + 2) . pack("C2", $cmd, $scmd). $sendStr;
	strlen := len(res) + 2
	byteArr := make([][]byte, 3)

	byteArr[0] = []byte(strconv.Itoa(strlen))
	byteArr[1] = []byte(strconv.Itoa(cmd))
	byteArr[2] = []byte(strconv.Itoa(scmd))

	fmt.Println(res)
	return res, nil
}

func (p *Packet) Decod(data []byte) (*entity.Message, error) {
	res := &entity.Message{}
	err := msgpack.Unmarshal(data, res)
	if err != nil {
		return nil, err
	}
	return res, nil
	//$header = substr($str, 0, 4);
	//if(strlen($header) != 4) {
	//	return self::packFormat("packet length invalid", 100007);
	//} else {
	//	$len = unpack("Nlen", $header);
	//	$len = $len["len"];
	//	$result = substr($str, 6);
	//	if ($len != strlen($result) + 2) {
	//		//结果长度不对
	//		return self::packFormat("packet length invalid", 100007);
	//	}
	//
	//	if($format == 'msgpack') {
	//		$result = msgpack_unpack($result);
	//	}
	//	if(empty($result)) {
	//	//结果长度不对
	//	return self::packFormat("packet data is empty", 100008);
	//	}
	//	$cmd = unpack("Ccmd/Cscmd", substr($str, 4, 6));
	//	$result = self::packFormat("OK", 0, $result);
	//	$result['cmd'] = $cmd['cmd'];
	//	$result['scmd'] = $cmd['scmd'];
	//	$result['len']  = $len + 4;
	//	return $result;
	//}
}

func (p *Packet) Format(msg string, code int, data interface{}) {
	//	$pack = array(
	//		"code" => $code,
	//		"msg" => $msg,
	//		"data" => $data,
	//);
	//	return $pack;
}
